<?php

namespace App\Recharge\Api;

use App\Models\Admin\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Weiyunka extends AbstractApi
{
    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key): string
    {
        ksort($array); //排序post参数
        $signText='';
        foreach ($array AS $k => $val) { //遍历POST参数
            if ($val == '' || $k == 'sign') continue; //跳过这些不签名
            if ($signText) $signText .= '&'; //第一个字符串签名不加& 其他加&连接起来参数
            $signText .= "$k=$val"; //拼接为url参数形式
        }
        return md5($signText . $secret_key);
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'userid'        => $bean->getSupplierNum(), //商户密钥
            'outorderno'    => $bean->getOrderNo(), //订单号
            'goodsid'       => $bean->getGoodsId(), //商品编码
            'buynum'        => $bean->getRechargeNum() * $bean->getStartCharging(),//充值数量,
            'attach'        => json_encode([$bean->getAccount()]),
            'callbackurl'   => $bean->getNotifyUrl(), //异步回调地址
            'maxmoney'      => $bean->getUnitPrice(),
        ];

        $array['sign'] = $this->sign($array, $bean->getSecretKey());

        return $array;
    }

    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('status', '');
        $order_sn = $request->input('orderno', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(true)->setRechargeSuccess($status == 5);
    }
}
